package com.qn.example.controller;

import com.qn.example.pojo.AddressBook;
import com.qn.example.pojo.R;
import com.qn.example.service.AddressBookService;
import com.qn.example.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 21276
 * @version 1.0
 * @date 2023/5/19 9:10
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Resource
    private AddressBookService addressBookService;

    @PostMapping
    public R saveAddressBook(@RequestBody AddressBook addressBook, HttpSession session){
        //获取当前的登录用户（客户端用户）
        Long userId = (Long) session.getAttribute("user");
        //补数据
        addressBook.setUserId(userId);
        addressBook.setCreateUser(userId);
        addressBook.setUpdateUser(userId);
        addressBookService.saveAddressBook(addressBook);
        return R.success("添加地址成功");
    }

    /**
     * 查询地址
     *
     */
    @GetMapping("/list")
    public R addressList(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        List<AddressBook> addressBooks = addressBookService.addressList(userId);
        return R.success(addressBooks);
    }

    /**
     * 修改默认地址
     */
    @PutMapping("/default")
    public R updateDefault(@RequestBody AddressBook addressBook,HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        addressBookService.updateDefault(addressBook,userId);
        return R.success("设置成功");
    }

    /**
     * 修改地址内容
     *      1.先按照地址的id查到当前地址，将地址对象返回
     *      2.修改回显数据，从新提交
     */
    @GetMapping("/{id}")
    public R getAddressById(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getAddressBookById(id);
        return R.success(addressBook);
    }


    /**
     * 修改地址
     */
    @PutMapping
    public R updateAddressBook(@RequestBody AddressBook addressBook){
        addressBookService.updateAddressBook(addressBook);
        return R.success("修改地址成功");
    }

    /**
     * 删除地址
     */
    @DeleteMapping
    public R deleteAddress(Long ids){
        addressBookService.deleteAddressByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 设置默认地址
     */

    @GetMapping("default")
    public R getDefaultAddressBook(HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        AddressBook addressBook = addressBookService.findDefaultAddressBook(userId);
        return R.success(addressBook);
    }
}
